// 业务逻辑相关

const dayjs = require("dayjs");
const User = require("./../dao/userDao");
const { ciphertext, compare } = require("@util/password");
const { JWT, ExpressJWT } = require("@util/jwt");

const computedUserInfo = async (phone, password) => {
  try {
    const users = await User.queryByPhone(phone);
    const time = dayjs().format("YYYY-MM-DD HH:mm:ss");
    if (users.length) {
      return Promise.resolve({
        has: true,
        userInfo: users[0],
      });
    } else {
      const pwd = await ciphertext(password);
      return Promise.resolve({
        has: false,
        userInfo: {
          phone,
          username: phone,
          password: pwd,
          createtime: time,
          updatetime: time,
        },
      });
    }
  } catch (error) {
    return Promise.reject(error);
  }
};

module.exports = {
  test: async (ctx, next) => {
    let code = ctx.request.body.code;
    let addparams = ["adwsd", 3, 2];
    let result = DB.add(addparams);
    console.log(result);
    ctx.response.body = {
      list: "",
      state: "测试成功",
      code: "0",
    };
  },

  saveUserInfo: ({ userInfo = {}, session_key = "", skey = "" }) => {
    return Users.saveUserInfo(userInfo, session_key, skey).then((res) => {
      return res;
    });
  },

  queryByPhoneAndPassword: async (req, res, next) => {
    try {
      const { phone, password } = req.body || {};
      console.log(phone, "[-");
      const user = await User.queryByPhone(phone);
      if (user.length) {
        const { id, phone, password: pwd } = user[0] || {};
        const bool = await compare(password, pwd);
        if (bool) {
          const jwt = new JWT();
          next({
            code: 200,
            data: {
              token: `Bearer ${jwt.sign(id, phone)}`,
            },
            msg: "成功~",
          });
        } else {
          next({
            code: 402,
            msg: "错误参数~",
          });
        }
      } else {
        next({
          code: 5003,
          msg: "数据不存在~",
        });
      }
    } catch (error) {
      next({
        code: 500,
        msg: error.message,
      });
    }
  },

  queryByPhone: async (req, res, next) => {
    const { phone, password } = req.body;
    if (!phone || !password) {
      next({
        code: 401,
        msg: "缺少参数~",
      });
    }
    try {
      const { has, userInfo = {} } = await computedUserInfo(phone, password);
      if (has) {
        next({
          code: 5002,
          msg: "数据已存在~",
        });
      } else {
        const result = await User.add(userInfo);
        const jwt = new JWT();
        next({
          code: 200,
          data: {
            token: `Bearer ${jwt.sign(result.insertId, userInfo.phone)}`,
          },
          msg: "成功~",
        });
      }
    } catch (error) {
      next({
        code: 500,
        msg: error.message,
      });
    }
  },
};
